package cxp.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;

/**
 * Created by cxp on 2018/5/24.
 */

public class JdbcUtils {

    private static String user = null;
    private static String password = null;
    private static String driver = null;
    private static String url = null;
    private static Connection conn = null;

    public static JdbcUtils db = null;
    private JdbcUtils(){

    }
    public static JdbcUtils getInstance(){
        if(db == null){
            synchronized(JdbcUtils.class){
                if(db == null){
                    db = new JdbcUtils();
                }
            }
        }
        return db;
    }
    //读取配置文件且加载数据库驱动
    static{
        ResourceBundle resource = ResourceBundle.getBundle("pro");
        String driver = resource.getString("database.driverClassName");
        url = resource.getString("database.url");
        user = resource.getString("database.username");
        password = resource.getString("database.password");
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //建立数据库的连接
    public Connection getConn(){
        try {
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
}
